import 'package:dart_style/dart_style.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:json_to_dart/src/replace/replace.dart';

import 'src/model_generator.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController inputController = TextEditingController();
  TextEditingController outputController = TextEditingController();
  TextEditingController classNameController = TextEditingController();

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    inputController.dispose();
    outputController.dispose();
    classNameController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        padding: EdgeInsets.all(32),
        child: Row(
          children: [
            Expanded(
                flex: 1,
                child: _TextField(
                  controller: inputController,
                  hintText: 'ApiFox生成的dart代码',
                )),
            tool(),
            Expanded(
                flex: 1,
                child: _TextField(
                  controller: outputController,
                )),
          ],
        ),
      ),
    );
  }

  Widget tool() {
    return Container(
      child: Column(
        children: [
          // Container(
          //     width: 150,
          //     child: TextField(
          //         controller: classNameController,
          //         decoration: InputDecoration(hintText: '类名，默认Sample'))),
          // TextButton(
          //   onPressed: () {
          //     generat();
          //   },
          //   child: Text('生成'),
          // ),
          TextButton(
            onPressed: () {
              Clipboard.setData(ClipboardData(text: outputController.text));
            },
            child: Text('复制结果'),
          ),
          TextButton(
            onPressed: () {
              _replace();
              // test();
            },
            child: Text('转换'),
          ),
        ],
      ),
    );
  }

  _replace() {
    var res = replace(inputController.text);

    final formatter = DartFormatter();
    outputController.text = DartCode(formatter.format(res), []).code;
  }

  generat() {
    final String className =
        classNameController.text.isEmpty ? 'Sample' : classNameController.text;
    final classGenerator = ModelGenerator(className);
    final jsonRawData = inputController.text;
    DartCode dartCode = classGenerator.generateDartClasses(jsonRawData);
    outputController.text = dartCode.result;
  }

  void test() {
    var res = '';
    // res =
    //     'chapters: List<CourseChapter>.from(json["chapters"].map((x) => CourseChapter.fromJson(x))),';
    // res = res.replaceAllMapped(
    //   RegExp(r'from\(json\["(\w+)"\]\.map'),
    //   (match) {
    //     print(match.group(1));
    //     return 'from((json["${match.group(1)}"] ?? []).map';
    //   },
    // );

    res = 'lesson: Lesson.fromJson(json["lesson"]),';
    res = res.replaceAllMapped(
      RegExp(r'(\w+):\s*(\w+)\.fromJson\(json\["(\w+)"]\)'),
      (match) {
        print(match.group(2));
        return 'json["${match.group(3)}"] == null ? null : ${match.group(1)}: ${match.group(2)}.fromJson(json["${match.group(3)}"])';
      },
    );
    print(res);
  }
}

class _TextField extends StatelessWidget {
  final TextEditingController? controller;
  final String? hintText;
  const _TextField({super.key, this.hintText, this.controller});

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.black12,
      child: TextField(
          controller: controller,
          maxLines: 10000,
          decoration: InputDecoration(hintText: hintText)),
    );
  }
}
